package com.tgy.files.controller;


import com.tgy.enums.ResponseStatusEnum;
import com.tgy.files.resource.FileResource;
import com.tgy.files.service.FileService;
import com.tgy.result.GraceJSONResult;
import com.tgy.util.AppFileUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Validated
@Api(value = "文件控制器", tags = {"文件管理"})
@RestController
@RequestMapping("/file")
public class FileController {

    final static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Resource
    private FileResource fileResource;

    @Resource
    private FileService fileService;

    /**
     * 上传单文件(此项目使用Oss)
     * @param userId 用户ID
     * @param type   照片类型（头像（）、文章等）
     * @param file   文件
     */
    @ApiOperation("上传单文件(此项目使用Oss)")
    @PostMapping("uploadFace")
    public GraceJSONResult uploadFace(String userId, String type, MultipartFile file) throws Exception {
        String path = "";
        if (file != null) {
            // 获得文件上传的名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String fileNameArr[] = fileName.split("\\.");
                // 获得后缀
                String suffix = fileNameArr[fileNameArr.length - 1];
                // 判断后缀符合我们的预定义规范
                if (!suffix.equalsIgnoreCase("png") &&
                        !suffix.equalsIgnoreCase("jpg") &&
                        !suffix.equalsIgnoreCase("jpeg")
                ) {
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }

                // 执行上传
//                path = uploaderService.uploadFdfs(file, suffix);          //fastdfs
                path = fileService.uploadOSS(file, userId,type, suffix);    //oss
//                path = uploaderService.uploadOSS(file, userId, suffix);

            } else {
                return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        logger.info("path = " + path);

        String finalPath = "";
        if (StringUtils.isNotBlank(path)) {
//            finalPath = fileResource.getHost() + path;        //fastdfs
            finalPath = fileResource.getOssHost() + path;       //oss
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }

//        return GraceJSONResult.ok(doAliImageReview(finalPath));
        return GraceJSONResult.ok((Object) finalPath);
    }

    /**
     * 上传多个文件(使用的阿里云OSS)
     * @param userId  用户ID
     * @param files   文件
     */
    @ApiOperation("上传多个文件(使用的阿里云OSS)")
    @PostMapping("uploadSomeFiles")
    public GraceJSONResult uploadSomeFiles(String userId, MultipartFile[] files) throws Exception {
        // 声明list，用于存放多个图片的地址路径，返回到前端
        List<String> imageUrlList = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = "";
                if (file != null) {
                    // 获得文件上传的名称
                    String fileName = file.getOriginalFilename();

                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String fileNameArr[] = fileName.split("\\.");
                        // 获得后缀
                        String suffix = fileNameArr[fileNameArr.length - 1];
                        // 判断后缀符合我们的预定义规范
                        if (!suffix.equalsIgnoreCase("png") &&
                                !suffix.equalsIgnoreCase("jpg") &&
                                !suffix.equalsIgnoreCase("jpeg")
                        ) {
                            continue;
                        }

                        // 执行上传
//                        path = uploaderService.uploadFdfs(file, suffix);
                        path = fileService.uploadOSS(file, userId,null, suffix);

                    } else {
                        continue;
                    }
                } else {
                    continue;
                }

                String finalPath = "";
                if (StringUtils.isNotBlank(path)) {
//                    finalPath = fileResource.getHost() + path;
                    finalPath = fileResource.getOssHost() + path;
                    // FIXME: 放入到imagelist之前，需要对图片做一次审核
//                    finalPath = doAliImageReview(finalPath);//图片审核
                    imageUrlList.add(finalPath);
                } else {
                    continue;
                }
            }
        }

        return GraceJSONResult.ok(imageUrlList);
    }


    @ApiOperation("上传单个文件到本地服务器)")
    @PostMapping("uploadFile")
    public GraceJSONResult uploadFile(MultipartFile mf){
        Map<String, String> map = AppFileUtils.uploadFile(mf);
        return GraceJSONResult.ok((Object)map.get("path"));
    }

    /**
     * 从本地服务器下载文件
     */
    @ApiOperation("从本地服务器下载文件)")
    @GetMapping("downloadFile")
    public GraceJSONResult downloadFile(String path, HttpServletResponse response, String name){
        String stuff = path.substring(path.lastIndexOf("."));
        try {
            File file = AppFileUtils.createResponseEntity2(path, response, name + stuff);
            // ResponseEntity<Object> responseEntity = AppFileUtils.createResponseEntity(path);
            return GraceJSONResult.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return GraceJSONResult.error();
        }
    }

}
